#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Time    :   2021/06/06 16:11:48
@Author  :   Leo Wood 
@Contact :   leowood@foxmail.com
@Disc    :   分类模型启动脚本
'''


import spacy
import re
nlp = spacy.load("en_core_sci_sm")
from Seg_Sents_En_Z import seg_sens

from flask import Flask,request

import argparse

app = Flask(__name__)



parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)


## some parameters

parser.add_argument("--api_server_ip", type=str, default='127.0.0.1',
                    help="API Server IP,默认为本机127.0.0.1")

parser.add_argument("--api_server_port", type=int, required=True,
                    help="api_server端口号")


args = parser.parse_args()


def citation_mark(sen):
    tag = False
    brackets = re.compile(r'[(](.*?)[)]', re.S)
    # medium = re.compile(r"\[.*?\]",re.S)
    medium = re.compile(r"[[](.*?)[]]", re.S)
    link = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')  # 匹配模式

    url = re.findall(link, sen)

    ### [ ] and et al. and link
    if ("et?al." in sen) or ("et al." in sen) or (any(url_ in sen for url_ in url)) or (
            "▶" in sen) or ("ref." in sen.lower()):
        # if "et al." in text_list[i]:
        tag = True
        # break
    elif "[" in sen and "]" in sen:
        reg_list = re.findall(medium, sen)
        # print(reg_list)
        vim_list = [k.replace(",", "").replace(" ", "").replace('–', '').replace('-', '') for k in reg_list]
        # print(num_list)
        #         # print(num_list[j])
        if any(_.isdigit() for _ in vim_list):
            tag = True

    elif "(" in sen and ")" in sen:
        reg_list = re.findall(brackets, sen)
        num_list = [k.replace(",", "").replace(" ", "").replace('–', '').replace('-', '') for k in reg_list]
        # print(num_list)
        #         # print(num_list[j])
        if any(_.isdigit() for _ in num_list):
            tag = True
        # print(text_list[i])
        # p1 = re.compile(r'[(](.*?)[)]', re.S)

    else:
        doc = nlp(sen)
        ner_list = [X.label_ for X in doc.ents]
        if 'PERSON' in ner_list and "DATE" in ner_list:
            # print()
            tag = True
    return tag

def predict(text):
    text = text.strip()
    sens = []
    for line in seg_sens(text):
        if citation_mark(line):
            sens.append(line)
    return sens



@app.route('/Cla_Result', methods=['GET','POST'])
def Cla_Result():
    if request.method == 'GET':
        text = request.args.get("text")

        sens = predict(text)

        return {'gold_sens':sens}

    if request.method == 'POST':
        text = request.form["text"]

        sens = predict(text)

        return {'gold_sens':sens}



if __name__ == "__main__":
    app.run(args.api_server_ip, port=args.api_server_port,debug=False)

    # lines = ['I have a good day',
    #         'You have a good day',
    #         'This paper aims to solve the math problem.']

    # text = "I have a good day. You have a good day. This paper aims to solve the math problem."
    # predict_lines(text)
